<template>
  <div>
    <el-dialog
      :visible.sync="isVisible"
      title="角色授权"
      center
      width="500px"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
    >
      <el-tree ref="tree" :data="auths" node-key="id" :props="defaultProps" show-checkbox default-expand-all />
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isVisible = false">
          取 消
        </el-button>
        <el-button
          type="primary"
          size="mini"
          :loading="loading"
          @click="authHandle()"
        >
          确 定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'RoleAuth',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      auths: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      loading: false
    }
  },
  computed: {
    isVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    isVisible(val) {
      if (val) {
        this.listAuth()
      }
    }
  },
  methods: {
    listAuth() {
      this.data = []
      this.AjaxUtils.get('/role/listAuthorize', { roleId: this.roleId }).then(response => {
        this.auths = response.data
        const roleHaveIds = response.roleHaveIds
        this.$refs.tree.setCheckedKeys(roleHaveIds)
      })
    },
    authHandle() {
      // make
      const checkedNodes = this.$refs.tree.getCheckedNodes()
      let permissionIds = ''
      checkedNodes.forEach(item => {
        permissionIds = permissionIds + item.id + ','
      })
      // params
      const params = new URLSearchParams()
      params.append('roleId', this.roleId)
      params.append('permissionIds', permissionIds)
      // ajax
      this.loading = true
      this.AjaxUtils.post('/role/authorize', params, true).then(response => {
        this.loading = false
        this.isVisible = false
        this.$emit('reloadTable')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
